#include "DbStorage/CreateProjectStorageCmd.hpp"
#include "CaseDB/Connection.hpp"
#include "CaseDB/Statement.hpp"
#include "CaseDB/RecordSet.hpp"
#include "CaseDB/DatabaseError.hpp"
#include "Storage/StorageError.hpp"
#include "Model/Project.hpp"
#include <cassert>

namespace DbStorage
{


CreateProjectStorageCmd::CreateProjectStorageCmd( Model::Project& rSubject, CaseDB::Connection& dbConnection )
: DbStorageCmd( rSubject, Storage::StorageCommand::Create, dbConnection)
{
}

// ---------------------------------------------------------------------------------------------------------------------

void CreateProjectStorageCmd::execute()
{
	using namespace CaseDB;

	try
	{
		Model::Project& project = dynamic_cast< Model::Project&>( rSubject_);

		RecordSet::Metadata rsMetadata;
		rsMetadata.push_back( DbTypesEnum::Integer);
		RecordSet result( rsMetadata);

		Statement insertStatement( "{? = call CREATE_PROJECT( ?, ?)}");
		insertStatement.addParameter( DbTypesEnum::Integer);
		insertStatement.addParameter( DbTypesEnum::String, project.name());
		insertStatement.addParameter( DbTypesEnum::String, project.description());
		dbConnection_.execute( insertStatement, result);

		//assert( result.numberOfRecords() == 1);
		//boost::any projectID = (*result.recordsBegin())[0];

		boost::any projectID = insertStatement.paramsBegin()->value();
		assert( !projectID.empty());
		project.setStoredID( projectID);
	}
	catch( CaseDB::DatabaseError& error)
	{
		throw Storage::StorageError( error.what() ? error.what() : "");
	}
}

} // namespace DbStorage
